import React, { useState } from 'react';
import './Add.css';
import axios, { ApiResponse } from './axios.ts';
import { Button, message, Input, Form } from 'antd';
import DtAddress from "../comment/map/DtAddress";
import { useNavigate } from 'react-router-dom';
import UploadComponent from './components/Upload.tsx';
import { UploadFile } from 'antd/es/upload';

const { TextArea } = Input;

interface FormValues {
  title: string;
  address?: string;
}

const Add: React.FC = () => {
  const [form] = Form.useForm<FormValues>();
  const [fileList, setFileList] = useState<UploadFile<any>[]>([]);
  const [uploading, setUploading] = useState<boolean>(false);
  const [currentUploadType, setCurrentUploadType] = useState<'image' | 'video'>('image');
  const navigator = useNavigate();

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();

      if (fileList.length === 0) {
        message.error('请选择要上传的图片或视频');
        return;
      }

      const fileObj = fileList[0].originFileObj;
      if (!fileObj) {
        message.error('请选择要上传的图片或视频');
        return;
      }

      // 检查文件类型
      const isImage = fileObj.type.startsWith('image/');
      const isVideo = fileObj.type.startsWith('video/');
      
      if (!isImage && !isVideo) {
        message.error('只能上传图片或视频文件');
        return;
      }

      setUploading(true);

      const submitFormData = new FormData();
      submitFormData.append('title', values.title);
      submitFormData.append('address', sessionStorage.getItem("address") || '');
      submitFormData.append('media_type', isVideo ? 'video' : 'image');
      submitFormData.append('file', fileObj);
      
      const userId = localStorage.getItem("user_id");
      submitFormData.append('user_id', userId || '');

      const response = await axios.post<ApiResponse>('/llx/add', submitFormData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      });

      if (response.data.code === 200) {
        message.success('发布成功');
        form.resetFields();
        setFileList([]);
        // 添加跳转逻辑
        navigator('/sendList');
      } else {
        message.error(response.data.message || '发布失败');
      }
    } catch (error: any) {
      if (error.errorFields) {
        message.error('请填写必填项');
      } else {
        console.error('提交错误:', error);
        message.error(error.response?.data?.message || '发布失败，请稍后重试');
      }
    } finally {
      setUploading(false);
    }
  };

  const tiaozhuan = () => {
    navigator('/send?id=1');
  };

  return (
    <div className="add-container">
      <Form form={form} className="add-form">
        <h2>添加新内容</h2>

        <Form.Item
          name="title"
          rules={[{ required: true, message: '请输入标题' }]}
        >
          <Input placeholder="请输入标题" />
        </Form.Item>

        <div className="form-group">
          <label>图片/视频</label>
          <UploadComponent 
            fileList={fileList} 
            setFileList={setFileList} 
            accept="image/*,video/mp4,video/webm,video/ogg" 
          />
          {fileList.length > 0 && (
            <div className="upload-status">
              已选择: {fileList[0].name}
            </div>
          )}
        </div>

        <div onClick={tiaozhuan}>
          <DtAddress />
        </div>

        <Button
          type="primary"
          onClick={handleSubmit}
          loading={uploading}
          style={{ width: '100%', marginTop: 20 }}
        >
          {uploading ? '提交中...' : '提交'}
        </Button>
      </Form>
    </div>
  );
};

export default Add;